<?php


namespace app\common\command;


use app\common\model\UserPush;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Log;

class CliTest extends Command
{
    /**
     * 命令配置
     */
    protected function configure()
    {
        $this->setName('cli:test')->setDescription('代码测试');
    }

    protected function execute(Input $input, Output $output)
    {
        print_r('推送开始' . PHP_EOL);
        $userPushModel = (new UserPush());
        $page = 1;
        $pushNum = 0;
        $userPushModel = $userPushModel->whereIn('status', [0, 1])->where('push_type', 5);
        // if ($jobData['hwPushType'] == 2)
        // { // 标签推送
        //     $tag = explode(',', $jobData['tag']);
        //     $userPushModel->whereIn('version', $tag);
        // }
        $totalNum = $userPushModel->group('regid')->count();

        $lastPage = (int)(ceil($totalNum / 2500));

        do
        {
            $userPushModel = $userPushModel->whereIn('status', [0, 1])->where('push_type', 5);
            // if ($jobData['hwPushType'] == 2)
            // { // 标签推送
            //     $tag = explode(',', $jobData['tag']);
            //     $userPushModel->whereIn('version', $tag);
            // }
            $pushData = $userPushModel->group('regid')->page($page, 2500)->column('regid');
            $excleData = [];
            foreach ($pushData as $regid)
            {
                $excleData[] = [$regid];
            }
            $this->AddData($excleData,'regids');
            $num = count($pushData);
            $pushNum += $num;
            $progress = sprintf('%.2f', $pushNum / $totalNum * 100);
            print_r(date('Y-m-d H:i:s') . '华为推送' . $num . "条完成,推送进度{$progress}%,推送数量{$pushNum}/{$totalNum},总页数{$lastPage},当前页数{$page}：休息1秒" . PHP_EOL);
            $page++;
            usleep(100000);
        } while ($page <= $lastPage);
        print_r('推送结束');
    }

    protected function AddData($data, $name)
    {
        $fileDir = RUNTIME_PATH . 'count';
        //判断目录是否存在
        !is_dir($fileDir) && mkdir($fileDir, 0755, true);
        $filename = $fileDir . DS . $name . '.csv';
        //文件存在则写入，文件不存在则创建
        $handle = fopen($filename, 'ab+');
        //解决excel乱码问题
        fwrite($handle, chr(0xEF) . chr(0xBB) . chr(0xBF));

        //循环数组写入data
        if ($data)
        {
            foreach ($data as $value)
            {
                fputcsv($handle, $value);
            }
        }
        print('统计' . $name . '完成' . PHP_EOL);
        fclose($handle);
        return true;
    }
}
